#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include "log.hpp"


#define pathname "/home/cyq_17/"
#define proj_id 0x8866
#define size 4096

Log log;

int GetKey()
{
    key_t key=ftok(pathname,proj_id);
    if(key<0)
    {
        log(Fatal,"creat key error: %s",strerror(errno));
        exit(1);
    }

    log(Info,"creat key success: %d",key);

    return key;
}

int GetShareMemHelper(int flag)
{
    key_t key=GetKey();
    int shmid=shmget(key,size,flag);
    if(shmid<0)
    {
        log(Fatal,"creat shmid error: %s",strerror(errno));
        exit(1);
    }

    log(Info,"creat shmid success: %d",shmid);
    return shmid;
}

int CreatShm()
{
    return GetShareMemHelper(IPC_CREAT|IPC_EXCL|0666);
}

int GetShm()
{
    return GetShareMemHelper(IPC_CREAT);
}

#define FIFO_FILE "myfifo"
#define MODE 0664

enum
{
    FIFO_CREAT_ERR = 1,
    FIFO_DELETE_ERR = 2,
    FIFO_OPEN_ERR = 3,
};

class Init
{
public:
    Init()
    {
        // 创建管道
        int n = mkfifo(FIFO_FILE, MODE);
        if (n == -1)
        {
            perror("mkfifo");
            exit(FIFO_CREAT_ERR);
        }
    }

    ~Init()
    {
        // 删除信道
        int m = unlink(FIFO_FILE);
        if (m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};

#endif